package coolq.yaozhenyong.custom;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.forte.qqrobot.beans.messages.msgget.GroupMsg;
import com.forte.qqrobot.sender.MsgSender;
import com.forte.qqrobot.utils.CQCodeUtil;

import coolq.yaozhenyong.bean.OpenLayout;
import coolq.yaozhenyong.bean.SysUser;
import coolq.yaozhenyong.cocApi.custom.ClansClanTagCustom;
import coolq.yaozhenyong.cocApi.custom.ClansPlayersTagCustom;
import coolq.yaozhenyong.cocApi.custom.CocApiAndCqCustom;
import coolq.yaozhenyong.cocApi.custom.QueryPlayersTagCustom;
import coolq.yaozhenyong.cocApi.entity.ClansClanTag.ClansClanTag;
import coolq.yaozhenyong.cocApi.entity.ClansClanTag.MemberList;
import coolq.yaozhenyong.cocApi.entity.ClansPlayersTag.ClansPlayersTag;
import coolq.yaozhenyong.cocApi.entity.QueryPlayers.QueryClan;
import coolq.yaozhenyong.service.SysUserService;

public class CocCustom {
	/***
	 * 查询部落信息，并返回信息
	 * 
	 * @param substring  查询的内容
	 * @param tag        查询的标签
	 * @param msg        群监听器
	 * @param cqCodeUtil 特殊代码合成器
	 * @param msgsender
	 * @return
	 */
	public static String goCocUrl(String substring, String tag, GroupMsg msg, CQCodeUtil cqCodeUtil,
			MsgSender msgsender) {
		switch (substring) {
		case "查询部落":
			ClanTag(tag, msg, cqCodeUtil, msgsender);
			break;
		case "查询村庄":
			PlayersTag(tag, msg, cqCodeUtil, msgsender);
			break;
		case "我的村庄":
			PlayersTag(tag, msg, cqCodeUtil, msgsender);
			break;
		case "查询玩家":
			PlayersTag(tag, msg, cqCodeUtil, msgsender);
			break;
		case "村庄":
			PlayersTag(tag, msg, cqCodeUtil, msgsender);
			break;
		case "部落":
			ClanTag(tag, msg, cqCodeUtil, msgsender);
			break;
		case "我的":
			ClanTag(tag, msg, cqCodeUtil, msgsender);
			break;
		case "查询部落配置":
			QueryClanTag(tag, msg, cqCodeUtil, msgsender);
			break;
		case "部落配置":
			QueryClanTag(tag, msg, cqCodeUtil, msgsender);
			break;
		default:
			msgsender.SENDER.sendPrivateMsg("936642284", " 查询出现错误，出现在代码CocCustom 44行，找不对对应属性！");
			break;
		}
		return null;
	}
	
	/****
	 * 查询村庄
	 * 
	 * @param tag
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 */
	private static void PlayersTag(String tag, GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender) {
		ClansPlayersTag findAll = ClansPlayersTagCustom.findAll(tag);
		SysUser sys = new SysUser();
		String gomsg = "";
		if (findAll.getDataisnull()) {
			SysUserService sysuserservice = SpringContextUtil.getBean(SysUserService.class);
			sys = sysuserservice.query().eq("username", msg.getGroup()).one();
			Boolean administratoring = sys.getAdministratoring() == null ? false : sys.getAdministratoring();
			if (sys != null && administratoring == true) {
				/** 合作用户 */
				// UserPlayersAdmin(findAll);
				String image = "";
				if(findAll.getLeague()!=null&&findAll.getLeague().getIconUrls()!=null&&findAll.getLeague().getIconUrls().getSmall()!=null) {
					image = "[CQ:image,file=" + findAll.getLeague().getIconUrls().getSmall() + "]";
				}
				gomsg += UserPlayersGo(findAll, image,cqCodeUtil,msg,tag);
				msgsender.SENDER.sendGroupMsg(msg.getGroupCode(),gomsg);
				/*msgsender.SENDER.sendPrivateMsg(msg.getQQ(), ""
						+ "● 点击查看【#"+tag+"】村庄详情!\n"
						+ "● 双击部落可查看部落信息！\n"
						+ "● 备用链接：http://yzycoc.com:8080/qqrobot/cocApi/playercoc?tag="+tag);*/
				//msgsender.SENDER.sendPrivateMsg(msg.getQQ(), "[CQ:share,url=http://yzycoc.com:8080/qqrobot/cocApi/playercoc?tag="+tag+",title=#"+tag+",content=点击查看村庄详细信息！,image=https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1550589518,1427910466&fm=26&gp=0.jpg]");
			} else {
				/** 非合作用户 */
				gomsg += UserPlayersGo(findAll, "",cqCodeUtil,msg,tag);
				msgsender.SENDER.sendGroupMsg(msg.getGroupCode(),gomsg);
				/*msgsender.SENDER.sendPrivateMsg(msg.getQQ(), ""
						+ "● 点击查看【#"+tag+"】村庄详情!\n"
						+ "● 双击部落可查看部落信息！\n"
						+ "● 备用链接：http://yzycoc.com:8080/qqrobot/cocApi/playercoc?tag="+tag);*/
				//msgsender.SENDER.sendPrivateMsg(msg.getQQ(), "[CQ:share,url=http://yzycoc.com:8080/qqrobot/cocApi/playercoc?tag="+tag+",title=#"+tag+",content=点击查看村庄详细信息！,image=https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1550589518,1427910466&fm=26&gp=0.jpg]");
			}
		} else {
			gomsg += findAll.getError();
			msgsender.SENDER.sendGroupMsg(msg.getGroupCode(), cqCodeUtil.getCQCode_At(msg.getQQ()) + gomsg);
		}
	}

	/***
	 * 查询部落
	 * 
	 * @param tag
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 */  
	public static void ClanTag(String tag, GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender) {
		ClansClanTag findAll = ClansClanTagCustom.findAll(tag);
		String gomsg = " ";
		if (findAll.getDataisnull()) {
			SysUserService sysuserservice = SpringContextUtil.getBean(SysUserService.class);
			SysUser sys = sysuserservice.query().eq("username", msg.getGroup()).one();
			Boolean administratoring = sys.getAdministratoring() == null ? false : sys.getAdministratoring();
			String image = "";
			if (sys != null && administratoring==true && findAll.getBadgeUrls()!=null && findAll.getBadgeUrls().getSmall()!=null &&Integer.parseInt(findAll.getClanLevel())<20) {
				image = "[CQ:image,file=" + findAll.getBadgeUrls().getSmall() + "]";
			}
			gomsg += UserClanGo(findAll);
			msgsender.SENDER.sendGroupMsg(msg.getGroupCode(), image+cqCodeUtil.getCQCode_At(msg.getQQ())+ gomsg);
			/** 普通用户把成员发送给他 **/
			/*msgsender.SENDER.sendPrivateMsg(msg.getQQ(), ""
					+ "● 点击查看【#"+tag+"】部落详情！\n"
					+ "● 双击村庄可以查看村庄详情！\n"
					+ "● 备用链接：http://yzycoc.com:8080/qqrobot/cocApi/clancoc?tag="+tag);*/
			//msgsender.SENDER.sendPrivateMsg(msg.getQQ(), "[CQ:share,url=http://yzycoc.com:8080/qqrobot/cocApi/clancoc?tag="+tag+",title=#"+tag+",content=点击查看部落详细信息！,image=https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=1550589518,1427910466&fm=26&gp=0.jpg]");
		} else {
			gomsg += findAll.getError();
			msgsender.SENDER.sendGroupMsg(msg.getGroupCode(), cqCodeUtil.getCQCode_At(msg.getQQ()) + gomsg);
		}
	}

	/***
	 * 会员用户 ---- 村庄
	 * 
	 * @param findAll
	 */
	public static void UserPlayersAdmin(ClansPlayersTag findAll) {

	}

	/***
	 * 普通用户 ---- 村庄
	 *  数据合成
	 * @param findAll
	 * @param image
	 * @param msg2 
	 * @param cqCodeUtil 
	 * @param tag 
	 * @return
	 */
	private static String UserPlayersGo(ClansPlayersTag findAll, String image, CQCodeUtil cqCodeUtil, GroupMsg msg2, String tag) {
		String max = "";
		if (findAll.getTownHallLevel() != null || findAll.getBuilderHallLevel() != null) {
			String getTownHallWeaponLevel = "";
			if (findAll.getTownHallWeaponLevel() != null) {
				getTownHallWeaponLevel = "(" + findAll.getTownHallWeaponLevel() + "星)";
			}
			if (findAll.getTownHallLevel() != null && findAll.getBuilderHallLevel() == null) {

				max = "[CQ:emoji,id=127751]" + findAll.getTownHallLevel() + "本" + getTownHallWeaponLevel + "\n";
			}
			if (findAll.getBuilderHallLevel() != null && findAll.getTownHallLevel() == null) {
				max = " [CQ:emoji,id=127747]" + findAll.getBuilderHallLevel() + "本\n";
			} else {
				max = "[CQ:emoji,id=127751]" + findAll.getTownHallLevel() + "本" + getTownHallWeaponLevel
						+ "  [CQ:emoji,id=127747]" + findAll.getBuilderHallLevel() + "本\n";
			}
		}
		String legendTrophies = "";
		if (findAll.getLegendStatistics() != null) {
			legendTrophies = findAll.getLegendStatistics().getLegendTrophies();
			if (legendTrophies != null) {
				legendTrophies = "传奇[CQ:emoji,id=127941]" + legendTrophies;
			} else {
				legendTrophies = "";
			}
		}
		String gototype = "";
		if (findAll.getGototype() == null) {
			gototype = "";
		} else {
			gototype = "\n" + findAll.getGototype();
		}
		String clanName = "";
		if (findAll.getClan() != null) {
			clanName = findAll.getClan().getName() != null
					? (findAll.getClan().getName() + "[" + findAll.getClan().getClanLevel() + "级]")
					: "无部落";
		} else {
			clanName = "无部落";
		}
		String url = DlCustom.dl("http://yzycoc.com/qq/cocApi/playercoc?tag="+tag);
		String role = findAll.getRole() != null ? findAll.getRole() : "无部落";
		String msg = image +cqCodeUtil.getCQCode_At(msg2.getQQ())+"\n● "+ findAll.getName() + "\n" + "[CQ:emoji,id=127991]" + findAll.getTag() + "\n"
				+ "[CQ:emoji,id=127984]" + clanName + "\n"
				/* + "职位："+cocTag+"\n"+ */
				+ max + "[CQ:emoji,id=127993]" + CocApiAndCqCustom.CocRole(role) + "[CQ:face,id=144]"
				+ findAll.getExpLevel() + "级\n" + "[CQ:emoji,id=127942]" + findAll.getTrophies() + legendTrophies + "\n"
				+ "[CQ:emoji,id=9876]" + findAll.getAttackWins() + "场 [CQ:emoji,id=128737]" + findAll.getDefenseWins()
				+ "场" + "\n● 捐:" + findAll.getDonations() + " ● 收:" + findAll.getDonationsReceived() + "\n● 历史最高：\n"
				+ "[CQ:emoji,id=127751][CQ:emoji,id=127942]" + findAll.getBestTrophies()
				+ "[CQ:emoji,id=127747][CQ:emoji,id=127942]" + findAll.getBestVersusTrophies()
				+ "\n● 详细信息\n[CQ:emoji,id=127758] "+url+ gototype;
		return msg;
	}

	/***
	 * 普通用户 --- 部落
	 * 
	 * @param findAll
	 * @return
	 */
	public static String UserClanGo(ClansClanTag list) {
		String msg = "";
		msg = "\n[CQ:emoji,id=9876]" + list.getName() + "\n" + "[CQ:emoji,id=127991]" + list.getTag() + "["
				+ list.getClanLevel() + "级]" + "\n[CQ:emoji,id=128694]现已有" + list.getMembers() + "人\n" + "[CQ:emoji,id=127751]奖杯："
				+ list.getClanPoints() + "\n" + "[CQ:emoji,id=127747]奖杯：" + list.getClanVersusPoints();
		/** 统计COC奖杯情况 **/
		String tro[][]= {{"传奇","0"},{"泰坦","0"},{"冠军","0"},{"水晶","0"},{"金杯","0"},{"银杯","0"},{"铜杯","0"},{"无杯","0"}};
		List<MemberList> memberList = list.getMemberList();
		for (MemberList m : memberList) {
			String trophies = CocApiAndCqCustom.trophies(m.getTrophies());
			for (int i = 0; i < tro.length; i++) {
				if(tro[i][0].equals(trophies)) {
					tro[i][1] = Integer.parseInt(tro[i][1]) + 1 + "";
					break;
				}
			}
		}
		String trophie = "";
		for (int i = 0; i < tro.length; i++) {
			if(!tro[i][1].equals("0")) {
				trophie +="\n● "+tro[i][0]+":"+tro[i][1]+"人";
			}
		}
		//接口异常提示
		String gototype = "";
		if (list.getGototype() == null) {
			gototype = "";
		} else {
			gototype = "\n" + list.getGototype();
		}
		String url =  DlCustom.dl("http://yzycoc.com/qq/cocApi/clancoc?tag="+list.getTag().substring(1, list.getTag().length()));
		msg +=trophie+"\n● 详细信息\n[CQ:emoji,id=127758] "+url
				+ gototype;
		
		return msg;
	}
	/***
	 * 查询部落配置
	 * @param tag
	 * @param msg
	 * @param cqCodeUtil
	 * @param msgsender
	 */
	private static void QueryClanTag(String tag, GroupMsg msg, CQCodeUtil cqCodeUtil, MsgSender msgsender) {
		QueryClan getmembers = QueryPlayersTagCustom.getmembers(tag);
		if(getmembers!=null) {
			//查询到信息，接下来返回结果给用户
			boolean main = CocImageClan.Query(getmembers,tag);
			msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ())+"[CQ:image,file=部落配置"+tag+".png]");
		}else {
			msgsender.SENDER.sendGroupMsg(msg.getGroup(), cqCodeUtil.getCQCode_At(msg.getQQ()) +" 无法查询到【#"+tag+"】的相关信息");
		}
	}
	
	public static String toyuqing(String html) {
		String rtmsg = "\n";
		String[] split = html.split("<b>");
		String regEx="\\D";
		for (int o = 0; o < split.length; o++) {
			String string = split[o];
			if(string.indexOf("</b>")!=-1) {
				String[] split2 = string.split("小时");
				String substring = "";
				if(string.indexOf("分钟")!=-1) {
					for (int i = 0; i < split2.length; i++) {
						Pattern p=Pattern.compile(regEx);
						Matcher m=p.matcher(split2[i]);
						String result=m.replaceAll("").trim();
				        Character ch=result.charAt(0);
				        substring += split2[i].substring(split2[i].indexOf(ch), split2[i].indexOf(ch)+2);
				        if(split2.length==2) {
				        	if(i==0) {
				        		substring +="小时";
				        	}else {
				        		substring +="分钟";
				        	}
				        }
				        if(split2.length==1) {
				        	substring +="分钟";
				        }
					}
				}else {
					substring +="不久之";
				}
				
				String satate = string.substring(0, string.indexOf("</b>"));
				substring = substring.replaceAll(" ", "");
				if(o == 1) {
					rtmsg += "[CQ:emoji,id=128293]现在鱼情状态为"+satate+"，将持续"+substring;
				}else if(o==2) {
					rtmsg += "\n①预计"+substring+"后状态转为"+satate;
				}else if(o==3) {
					rtmsg += "\n②预计"+substring+"后状态转为"+satate;
				}
			}
		}
		return rtmsg;
	}
	private static String[] yq = {"",""};
	public static String goyuqing() {
		try {
			Map<String,Object> data = new HashMap<String,Object>();
			String url = "";
			try {
				url = BackEndHttpRequest.getURL("http://www.clashofclansforecaster.com/STATS.json", data, "GET");
			} catch (Exception e) {
				return null;
			}
			if(url=="") {
				return null;
			}
			JSONObject jsonx = JSON.parseObject(url); 
			JSONObject loot = jsonx.getJSONObject("currentLoot");
			Integer totalPlayers = loot.getInteger("totalPlayers");//总玩家
			Integer playersOnline = loot.getInteger("playersOnline");//在线玩家
			Integer integer = loot.getInteger("playersOnlineChange");//在线人数变化情况
			Integer integer2 = loot.getInteger("shieldedPlayers");//有护盾的玩家
			Integer integer3 = loot.getInteger("shieldedPlayersChange");//有护盾的玩家的变化
			Integer integer4 = loot.getInteger("attackablePlayers");//可攻击的玩家
			Integer integer5 = loot.getInteger("attackablePlayersChange");//可攻击玩家的变化
			JSONArray object = (JSONArray) jsonx.getJSONArray("regionStats").get(0);
			Integer integer6 = object.getInteger(6);//中国人数
			Integer integer7 = object.getInteger(7);//中国人数变化
			String format = String.format("%.1f", (float) playersOnline / (float) totalPlayers * 100);
			String format2 = String.format("%.1f", (float) (totalPlayers-playersOnline) / (float) totalPlayers * 100);
			String format3 = String.format("%.1f", (float) integer2 / (float) totalPlayers * 100);
			String format4 = String.format("%.1f", (float) integer4 / (float) totalPlayers * 100);
			String format6 = String.format("%.1f", (float) integer6 / (float) totalPlayers * 100);
			String zx = "\n"+(integer>0?"↑":"↓")+"在    线:"+playersOnline+"("+format+"%)";
			String lx = "\n"+(integer>0?"↓":"↑")+"离    线:"+(totalPlayers-playersOnline)+"("+format2+"%)";
			String hd = "\n"+(integer3>0?"↑":"↓")+"有护盾:"+integer2+"("+format3+"%)";
			String kgj ="\n"+(integer5>0?"↑":"↓")+"可攻击:"+integer4+"("+format4+"%)";
			String zrs ="\n"+(integer7>0?"↑":"↓")+"[CQ:emoji,id=127464][CQ:emoji,id=127475]在线:"+integer6+"("+format6+"%)";
			//获取情况
			JSONObject jsonObject = jsonx.getJSONObject("forecastMessages");
			String string = jsonObject.getString("chinese-simp");
			String toyuqing = CocCustom.toyuqing(string);
			String toubu = "[CQ:emoji,id=127758]COC全球玩家状态";
			String yu  = yq[0];
			String urltm ="";
			if(yu != "") {
				long datadifference = TimeUtils.datadifference(yu);
				if(datadifference < 21600) {
					urltm = yq[1];
				}else {
					urltm = DlCustom.dl("http://www.clashofclansforecaster.com/?lang=chinese-simp");
					yq[0] = TimeUtils.getStringDate();
					yq[1] = urltm;
				}
			}else {
				urltm = DlCustom.dl("http://www.clashofclansforecaster.com/?lang=chinese-simp");
				yq[0] = TimeUtils.getStringDate();
				yq[1] = urltm;
			}
			String tohtml = "\n[CQ:emoji,id=127758]COC预报详情地址\n"+urltm;
			return toubu+zx+lx+hd+kgj+zrs+toyuqing+tohtml;
		} catch (Exception e) {
		}
		return null;
	}

	public static String OpenLayout(OpenLayout open) {
		String url = DlCustom.dl(open.getUrl());
		String re = "[CQ:face,id=190] 编号："+open.getNumber()+"\n[CQ:emoji,id=127758]"+url+"[CQ:image,file="+open.getImageUrl()+"]"+open.getRemark();
		return re;
	}

	
}
